import {NextFunction, Request, Response} from 'express'
import jwt from 'jsonwebtoken'
import config from '../config'

export const generateToken = (userId: string) => {
    const secretKey = config.security.secretKey;
    const expiresIn = config.security.expiresIn;
    return jwt.sign({
            userId
        }, secretKey,
        {
            expiresIn: expiresIn //过期时间
        })
}


export const checkToken = (req: Request, res: Response, next: NextFunction) => {
    // 获取请求头中的Authorization认证字符
    let authorization: any = req.get('Authorization');
    if (!authorization) {
        return res.json({
            errCode: 10005,
            msg: '需要携带Token值'
        })
    }
    let secretOrPrivateKey = config.security.secretKey;
    jwt.verify(authorization, secretOrPrivateKey, function (err: any, decode: any) {
        if (err) {  //  认证出错
            res.status(403).send({
                errCode: 10010,
                msg: '认证无效，请重新登录!'
            });
        } else {
            next();
        }
    })

}

export const analysisToken = (req: Request, res: Response, next: NextFunction) => {
    // 获取请求头中的Authorization认证字符
    let authorization: any = req.get('Authorization');
    if (!authorization) {
        return {
            errCode: 10005,
            msg: '需要携带Token值'
        }
    }
    let secretOrPrivateKey = config.security.secretKey;
    return new Promise((resolve,reject) => jwt.verify(authorization, secretOrPrivateKey, function (err: any, decode: any) {
        if (err) {  //  认证出错
            resolve({
                errCode: 10010,
                msg: '认证无效，请重新登录!'
            }) ;
        } else {
            resolve(decode)
        }
    }))


}
